# -*- coding: utf-8 -*-
# !/user/bin/env python
# -*- coding:utf-8 -*-

import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import weather
import countdown
import gold_price as gp
import news as ns

MAIL = {
    "from": 'aikesls@163.com',
    "pwd": 'PMVIUOVZURRSKWJD',
    "smtp": 'smtp.163.com',
}
receiver_list = ['aikesls@163.com', 'yuheng.yuan@macrowing.com', 'hanxiaorui@sx.chinamobile.com', '18835573213@163.com','2365346900@qq.com']
# receiver_list = ['aikesls@163.com']


def sendMail(content):
    msg = MIMEMultipart('alternative')
    msg['Subject'] = Header('综合批发市场的小助理', 'utf-8')  # 标题
    msg['From'] = MAIL['from']  # 发件人
    msg['To'] = ','.join(receiver_list)  # 多个收件人，用逗号分隔

    # 使用HTML格式来增加美观性
    html_message = MIMEText(content, 'html', 'utf-8')  # 正文
    html_message["Accept-Language"] = "zh-CN"
    html_message["Accept-Charset"] = "ISO-8859-1,utf-8"

    msg.attach(html_message)
    try:
        # 非SSL，如果为SSL则看下面
        server = smtplib.SMTP(MAIL['smtp'])

        # 如果是ssl，需要加多一个端口号映射
        # server = smtplib.SMTP_SSL()
        # server.connect(MAIL['smtp'],MAIL['port'])

        # 登陆邮箱发送邮件
        server.login(MAIL['from'], MAIL['pwd'])
        server.sendmail(MAIL['from'], receiver_list, msg.as_string())
        print('success')
    except Exception as e:
        print('error', e)


def assembleContent():
    # 计算假期
    holiday_counts = countdown.getHolidayInfo()
    # 定义天气信息
    weather_info = weather.get_all_cities_weather()
    # 获取当前金价
    # gold_price = gp.get_gold_price()
    # 获取新闻
    news = ns.get_news()

    # 生成 HTML 内容
    content = """
    <html>
        <head>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    color: #333333;
                    line-height: 1.6;
                    margin: 0;
                    padding: 20px;
                    background-color: #f4f4f4;
                }
                .container {
                    max-width: 600px;
                    margin: auto;
                    padding: 20px;
                    background-color: #ffffff;
                    border-radius: 8px;
                    box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
                }
                h1 {
                    color: #1a73e8;
                    text-align: center;
                    font-size: 24px;
                }
                table {
                    width: 100%;
                    margin-top: 20px;
                    border-collapse: collapse;
                }
                td {
                    padding: 10px;
                    text-align: center;
                    border: 1px solid #dddddd;
                }
                th {
                    background-color: #4CAF50;
                    color: white;
                    padding: 10px;
                    text-align: center;
                    font-size: 16px;
                }
                .highlight {
                    font-weight: bold;
                    color: #e74c3c;
                }
                .weather-table td {
                    background-color: #f1f1f1;
                }
                .weather-table th {
                    background-color: #3498db;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <h1>倒计时提醒</h1>
                <table>
                    <tr>
                        <th>节假日</th>
                        <th>剩余天数</th>
                    </tr>
    """
    # 添加节假日的倒计时信息
    for holiday_name, days_left in holiday_counts:
        content += f"""
                    <tr>
                        <td>{holiday_name}</td>
                        <td class="highlight">{days_left}</td>
                    </tr>
        """

    content += """
                  </table>
                  <h1>天气信息</h1>
                  <table class="weather-table">
                      <tr>
                          <th>城市</th>
                          <th>今天</th>
                          <th>明天</th>
                          <th>后天</th>
                      </tr>
      """

    # 添加天气信息，创建二维表格
    for city, forecasts in weather_info.items():
        content += f"<tr><td>{city}</td>"
        for forecast in forecasts[:3]:  # 假设每个城市最多有7天的预报
            date = forecast['date']
            weather_condition = forecast['weather']
            temperature = forecast['temperature']
            wind_directions = forecast['wind_directions']
            content += f"""
                          <td>
                              <p>{weather_condition}</p>
                              <p class="highlight" >{temperature}</p>
                              <p>{wind_directions}</p>
                          </td>
              """
        content += "</tr>"
    content += "</table>"
    # 添加金价信息
    # content += """
    #                <h1>当前金价：<span class="highlight" >{}<span></h1>
    # """.format(gold_price)  # 插入金价

    # 添加新闻信息
    content += """
                  <table>
                  <tr><th>科技新闻</th></tr>
      """
    for news_title, news_url in news.items():
        content += f"""
                      <tr><td><a href="{news_url}" target="_blank">{news_title}</a></td></tr>
        """
    content += '</table>'

    # 完成 HTML 内容
    content += """
            </div>
        </body>
    </html>
    """

    return content


if __name__ == '__main__':
    # print(assembleContent())
    sendMail(assembleContent())
